#define __LIBRARY__

#include <shm.h>
#include <stdio.h>
#include <sem.h>
#include <unistd.h>
#include <stdlib.h>

_syscall2(sem_t *, sem_open, const char *, name, unsigned int, value);
_syscall1(int, sem_wait, sem_t *, sem);
_syscall1(int, sem_post, sem_t *, sem);
_syscall1(int, sem_unlink, const char *, name);

_syscall2(int, shmget, key_t, key, size_t, size);
_syscall1(void *, shmat, int, shmid);

#define BUFSIZE 10
#define MAX_NUM 500

#define KEY 1024

sem_t *empty, *full, *mutex;

void consumer(int *p)
{
    int item_num, i;
    printf("I am a consumer, here are contents of consuming:\n");
    fflush(stdout);
    for (i = 0; i <= MAX_NUM; i++)
    {
        sem_wait(full);

        sem_wait(mutex);

        item_num = *(p + i % BUFSIZE);

        printf("item_num = %d\n", item_num);
        fflush(stdout);

        sem_post(mutex);

        sem_post(empty);
    }
    printf("Consumer, over.\n");
    fflush(stdout);
}

int main()
{

    long key = KEY;
    int shmid;
    int *p;

    empty = sem_open("empty", BUFSIZE);
    full = sem_open("full", 0);
    mutex = sem_open("mutex", 1);

    shmid = shmget(key, (MAX_NUM + 1) * sizeof(int));
    p = (int *)shmat(shmid);

    consumer(p);

    /* 此时生产者和消费者都不再使用信号量了，进行释放 */
    sem_unlink(empty);
    sem_unlink(full);
    sem_unlink(mutex);

    return 0;
}
